import { request, t } from 'utils'
import pageUtil from '../../lib/bh-vue/utils/pageUtil'
import { getPersonInfo  } from 'services/flow.service'

/**
 * 获取当前选择的数据及处理相关参数
 */
const getOptInfo = (vm, btnMeta, e) => {
  let records = []
  if (btnMeta.toolbar) {
    records = vm.$refs.listRef[0].checkedRecords()
  } else {
    const rowIndex = JSON.parse($(e.target).attr('data-index'))
    records = [vm.gridDatas.result.rows[rowIndex]]
  }
  
  let params = {}
  if (btnMeta.queryParam) {
    params = { ...(vm.$refs.listRef && vm.$refs.listRef[0].params || {}) }
  }

  if (btnMeta.selectType === 1) {
    const record = records[0]
    params.key = JSON.stringify({
      time: vm.gridTime,
      bizKey: record['$$bizKey'],
      sign: record['$$sign']
    })

    if (btnMeta.params) {
      params = { ...params, ...btnMeta.params.reduce((ret, item) => ({
        ...ret,
        [item.name]: item.value === undefined ? record[item.column] : item.value
      }), {})}
    }
  } else if (btnMeta.selectType === 2) {
    const keys = {'time': vm.gridTime, rows: []}
    records.forEach(record => {
      keys.rows.push({
        bizKey: record['$$bizKey'],
        sign: record['$$sign']
      })
    })
    params.keys = JSON.stringify(keys)
  }

  btnMeta.params && btnMeta.params.forEach(item => {
    if (item.value !== undefined) {
      params[item.name] = item.value
    }
  })

  if (btnMeta.toolbar) {
    if (btnMeta.selectType === 1 && (!records || records.length !== 1)) {
      console.warn('必须且只能选择一个元素进行编辑!')
      return
    }

    return {
      records: records,
      btnData: btnMeta,
      params,
    }
  } else {
    const rowIndex = JSON.parse($(e.target).attr('data-index'))
    records = [vm.gridDatas.result.rows[rowIndex]]

    return {
      records,
      rowIndex,
      btnData: btnMeta,
      params,
    }
  }
}

//新增，发起需要确认
const doFormTask = (vm, btnMeta, e) => {
  if(btnMeta.type === "add" || btnMeta.type === "apply"){
    try {
      getPersonInfo().then(res => {
        if(res){
          if(res.enable){
            const personOptions = {
              title: res.title,
              ok: "同意"
            }
            pageUtil.confirm(res.content, () => {
              doFormTaskFn(vm, btnMeta, e)
            },personOptions)
          }else{
            doFormTaskFn(vm, btnMeta, e)
          }
        }else{
          doFormTaskFn(vm, btnMeta, e)
        }
        
      })
    } catch (error) {
      console.log(error)
      doFormTaskFn(vm, btnMeta, e)
    }
  }else{
    doFormTaskFn(vm, btnMeta, e)
  }
}

// 表单任务
const doFormTaskFn = (vm, btnMeta, e) => {
  let parent = vm
  if (!parent.renderConnmon) {
    parent = vm.$parent
  }
  let { btnData, params } = getOptInfo(vm, btnMeta, e)

  if (btnData.selectType === 0) { // 不需要数据
    parent.renderConnmon(vm, btnData, undefined, {queryParams: params})
  } else { // 需要数据
    parent.renderConnmon(vm, btnData, params.key, {queryParams: params})
  }
}

/**
 * 流程任务
 */
const doFlowTask = (vm, btnMeta, e) => {
  const { btnData, params } = getOptInfo(vm, btnMeta, e)
  // vm.flowHandle(btnData, rowIndex)
  const run = () => {
    const url = '/sys/emapflow/' + btnData.path
    request(url, {
      query: {
        appName: vm.appName.name,
        ...params
      },
    }).then(res => {
      if(res.succeed) {
        pageUtil.tip('操作成功', 'success')

        if (btnData.refresh) {
          vm.$refs.listRef[0].reload()
        }
      }else{
        pageUtil.tip('操作失败', 'danger')
      }
    }).catch(e=>{
      pageUtil.tip(e, 'danger')
    })
  }
  //处理带有弹窗类型
  const dealDialog = () =>{
    const optUrl = vm.formUrl.replace('showForm.do', "getTask.do")
    request(optUrl, {
      query: { ...params, alias: vm.gridAlias },
    }).then(res => {
      if(res.code === '0') {
        const taskid = res.datas.taskId
        if(btnData.dialogName === "changeAssignee"){
          vm.$refs.person.queryOrganization(taskid, vm.appName.name)
        }else if(btnData.dialogName === "turnback"){
          vm.$refs.emapJump.initJump(taskid, vm.appName.name)
        }
      } else {
        pageUtil.tip(res.msg || '操作失败', 'danger')
      }
    }).catch(e => {
      pageUtil.tip(e, 'danger')
    })
  }
  if (btnData.confirm) {
    pageUtil.confirm(t(btnData.confirm, btnData.title), () => {
      if(btnData.dialogName){
        dealDialog()
      }else{
        run()
      }
    })
  } else {
    if(btnData.dialogName){
      dealDialog()
    }else{
      run()
    }
  }
}

const doOptTask = (vm, btnMeta, e) => {
  const { btnData, params } = getOptInfo(vm, btnMeta, e)
  // console.log('params', params)

  const run = () => {
    //loading
    vm.loading.open = true
    const optUrl = vm.formUrl.replace('showForm.do', btnData.opt)
    if(btnMeta.download){
      const queryData = {...params, alias: vm.gridAlias}
      // location.href = window.contextPath + exportUrl + "?alias="+ this.queryPath.params.alias +"&gridAlias="+ this.gridAlias
      // const queryString = Object.keys(queryData).map(name => `${name}=${encodeURIComponent(queryData[name])}`).join('&')
      // window.open(window.contextPath + optUrl +"?"+ queryString)
      postExcelFile(window.contextPath + optUrl, queryData)
      return
    }
    request(optUrl, {
      query: { ...params, alias: vm.gridAlias },
    }).then(res => {
      vm.loading.open = false
      if(res.code === '0') {
        pageUtil.tip(res.message || '操作成功', 'success')
        btnMeta.refresh && vm.$refs.listRef[0].reload()
      } else {
        pageUtil.tip(res.message || '操作失败', 'danger')
      }
    }).catch(e => {
      vm.loading.open = false
      pageUtil.tip(e, 'danger')
    })
  }

  if (btnData.confirm) {
    pageUtil.confirm(t(btnData.confirm, btnData.title), () => {
      run()
    })
  } else {
    run()
  }
}

 // 导出excel
 const postExcelFile = (url, params) => {
  //params是post请求需要的参数，url是请求url地址
  var form = document.createElement("form");
  form.style.display = "none";
  form.action = url;
  form.method = "post";
  try {
    document.body.appendChild(form);
    // 动态创建input并给value赋值
    for (var key in params) {
      var input = document.createElement("input");
      input.type = "hidden";
      input.name = key;
      input.value = params[key];
      form.appendChild(input);
    }

    form.submit();
  } catch (error) {
    console.error(error)
  } finally {
    form.remove();
  }
  
}

/**
 * 任务处理入口
 */
export const runTask = (vm, btnMeta, evt) => {
  if (!btnMeta && evt) {
    btnMeta =  JSON.parse($(evt.target).attr('data-item'))
  }

  switch(btnMeta.method) {
    case 'form': { // 需要显示表单
      doFormTask(vm, btnMeta, evt)
      break
    }
    case 'flow': { // 流程处理
      doFlowTask(vm, btnMeta, evt)
      break
    }
    case 'opt': { // 执行操作
      doOptTask(vm, btnMeta, evt)
      break
    }
    default: {
      console.warn('invalid button meta', btnMeta)
    }
  }
}
